<?php
/**  */

namespace backend\models;


use yii\base\Model;
use yii\filters\AccessControl;

class PermissionForm extends Model
{
    public $name;

    public $description;


    public function behaviors()
    {
        return [
            /*'access'=>[
                'class'=>AccessControl::className(),
                'rules'=>[
                    [
                        'allow'=>true,
                        'action'=>['save-permission'],
                        'matchCallback' => function ($rule,$action){
            var_dump($action);exit;
                            return \Yii::$app->user->isGuest?false:\Yii::$app->user->can($action->id);
                        }
                    ],
                ],
            ],*/
        ];
    }

    /**
     * 定义验证规则
     * @return array
     */
    public function rules()
    {
        return [
            [['name','description'],'required'],
            [['name'],'string','max'=>'64'],
            [['name'],'validatePermission'],
        ];
    }

    /**
     * 自定义验证规则 验证权限属性是否存在
     * @param $attributes  '需要验证的属性的名字' string|Array
     * @param $param '参数'
     */
    public function validatePermission($attributes, $param)
    {

        $auth =\Yii::$app->authManager;
        if(is_array($attributes)){
            foreach($attributes as $attribute){
                if($auth->getPermission($this->$attribute)){
                    $this->addError($attribute,'权限已存在');
                }
            }
        }else{
            /** getpermission 没有对应的权限是放回空 */
            if($auth->getPermission($this->$attributes)){
                $this->addError($attributes,'权限已存在');
            }
        }

    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'name'=>'名称',
            'description'=>'描述',
        ];
    }


    /**
     * 定义一个方法,根据传入的值,添加权限
     * @param string $name  权限的名称 路由
     * @param string $descripion 权限的描述
     * @return boolean 返回保存权限的结果
     */
    public static function savePermission( $name,  $descripion){
        //实例化RBAC权限认证管理对象
        $auth = \Yii::$app->authManager;
        $permission = $auth->createPermission($name);
        $permission->description = $descripion;
        //保存权限
        return $auth->add($permission);
    }


}